#!/usr/bin/python -S
"""
size_demo.py

Compare TNET vs JSON size.

Result: JSON usually smaller!  TNET is good for sipmle parsing, and tunneling
other serialization formats, but not for compactness.

Protobuf-like optimizations like "packed repeated fields", especially for
integers, would help a lot.
"""

__author__ = 'Andy Chu'


import sys

import tnet
import json


class Error(Exception):
  pass


def main(argv):
  """Returns an exit code."""
  objs = [
      6,
      3.14159,
      True,
      None,
      [],
      [1,2,3],
      ["one", "two", "three"],

      {},
      {"one": "two"},
      {"dictionary": "withmany", "longentries": "lets see"},

      {"one": ["two", "three"]},
      ]


  fmt = '%-35s %-35s %s'
  print fmt % ('JSON', 'TNET', '?')
  print fmt % ('----', '----', '-')
  for o in objs:
    j = json.dumps(o)
    t = tnet.dumps(o)
    len_j, len_t = len(j), len(t)
    op = '<' if len_j < len_t else '=' if len_j == len_t else '>'
    compare = "%2d %s %2d" % (len_j, op, len_t)
    print fmt % (j, t, compare)

  return 0


if __name__ == '__main__':
  try:
    sys.exit(main(sys.argv))
  except Error, e:
    print >> sys.stderr, e.args[0]
    sys.exit(1)
